
package com.cmc.dao.hibernate;

import java.util.List;

import com.cmc.dao.hibernate.BaseDaoHibernate;
import com.cmc.model.Reason;
import com.cmc.dao.ReasonDao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class ReasonDaoHibernate extends BaseDaoHibernate implements ReasonDao {

    /**
     * @see com.cmc.dao.ReasonDao#getReasons(com.cmc.model.Reason)
     */
    public List getReasons(final Reason reason) {
        //return getHibernateTemplate().find("from Reason");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.*/
        if (reason == null) {
            return getHibernateTemplate().find("from Reason");
        } else {
            // filter on properties set in the reason
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(reason).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Reason.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.cmc.dao.ReasonDao#getReason(Long id)
     */
    public Reason getReason(final Long id) {
        Reason reason = (Reason) getHibernateTemplate().get(Reason.class, id);
        if (reason == null) {
            log.warn("uh oh, reason with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(Reason.class, id);
        }

        return reason;
    }

    /**
     * @see com.cmc.dao.ReasonDao#saveReason(Reason reason)
     */    
    public void saveReason(final Reason reason) {
        getHibernateTemplate().saveOrUpdate(reason);
    }

    /**
     * @see com.cmc.dao.ReasonDao#removeReason(Long id)
     */
    public void removeReason(final Long id) {
        getHibernateTemplate().delete(getReason(id));
    }
}
